<template>
  <div style="height: calc(100% - 35px);display: flex;flex-direction: column;">
    <div class="header-bar" style="padding-top:10px;">
      <span class="float-left" style="line-height: 31px">
        <h3>权限配置{{ currentRole ? ':' + currentRole.name + ' - ' + currentRole.sn : '' }}</h3>
      </span>
      <ButtonGroup>
        <Button icon="h-icon-check" :loading="permissionSaving" @click="savePermission" :disabled="!currentRole">保存
        </Button>
      </ButtonGroup>
    </div>
    <div class="list" style="line-height: 30px;overflow-y: scroll;padding:10px;border:1px solid #eeeeee;">
      <div v-for="it in allPermission" :key="it.key">
        <h3 class="form-group-header">
          <Checkbox v-model="selectPermission" :value="it.key"><i :class="it.icon"></i>{{ it.title }}</Checkbox>
        </h3>
        <div v-for="sub in it.children" :key="sub.key" style="padding-left: 30px">
          <h4>
            <Checkbox v-model="selectPermission" :value="sub.key"><i :class="sub.icon"></i>{{ sub.title }}</Checkbox>
          </h4>
          <div style="padding-left:30px;">
                 <span style="display: inline-block;margin-right:20px" v-for="per in sub.children" :key="per.key">
                  <Checkbox v-model="selectPermission" :value="per.key"><i
                      :class="per.icon"></i>{{ per.title }}</Checkbox>
                </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {ajax} from 'framework'

export default {
  name: "RolePermission",
  props: {
    allPermission: Array,
    role: Object
  },
  data() {
    return {
      currentRole: null,
      permissionSaving: false,
      selectPermission: []
    }
  },
  mounted(){
    if(this.role){
      this.switchRole(this.role)
    }
  },
  watch: {
    role(v) {
      this.switchRole(v)
    }
  },
  methods: {
    switchRole(dt) {
      ajax.get('role/role_permission', {role: dt.sn}).then(r => {
        this.currentRole = dt
        this.selectPermission = r.data
      })
    },
    savePermission() {
      if (this.currentRole == null) {
        this.$Message("权限未选择")
        return
      }
      if (this.selectPermission == null) {
        this.selectPermission = []
      }
      this.permissionSaving = true
      ajax.post('role/save_role_permission', {
        role: this.currentRole.sn,
        permissions: this.selectPermission
      }).then(r => {
        this.$Message('已保存')
      }).finally(r => {
        this.permissionSaving = false
      })
    }
  }
}
</script>
<style>
  .h-checkbox-text{
    font-size: 13px;
    font-weight: normal;
  }
  .h-checkbox-text i{
    padding: 0px 3px 0px 6px;
  }
</style>
